<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-22 23:13:35
 * @LastEditTime: 2025-01-26 17:28:33
 * @FilePath: /env-manager-pc/src/views/system/access/index.vue
-->
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import Edit from './edit.vue'
import type { AccountForm } from './page'
import type { doLoading } from '@/types/page'
import { useEnvOrgs, useOwnerOrgs } from '@/utils/dataHook'
import { QueryObj } from '@/utils/dataHook/data'
import { usePage } from '@/utils/commonHook'
import userApi from '@/api/modules/user'
import { AccountType } from '@/api/modules/types/user'
import { ModelType } from '@/types/common'

const route = useRoute()

const AffiliatedObjType = computed(() => {
  switch (route.name) {
    case 'system-access-EnvOrg':
      return AccountType.EnvOrg
    case 'system-access-OwnerOrg':
      return AccountType.OwnerOrg
    case 'system-access-Enterpris':
      return AccountType.Enterpris
  }
})

const editRef = ref()

const searchData = reactive(new QueryObj({
  objType: 'DIM.FilterCollection',
  Filters: [{ Type: 'DIM.Authorizations.Filters.AffiliatedObjIDFilter',
    FilterKey: 'DIM.Authorizations.Filters.AffiliatedObjIDFilter',
    ObjType: AffiliatedObjType.value,
    valueKey: 'DIM.Authorizations.Filters.AffiliatedObjIDFilter' },
  'DIM.Authorizations.Filters.CodeFilter',
  'DIM.Authorizations.Filters.NameFilter', 'DIM.Authorizations.Filters.ContactTelFilter', 'DIM.Authorizations.Filters.MsgTelFilter'],
}))
const loading = ref(false)

const tableData = ref([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

const defaultProps = {
  children: 'Children',
  label: 'Name',
}
function search() {
  page.PageNum = 1
  getTableData()
}

async function getTableData() {
  loading.value = true
  const res = await userApi.GetAccountList({
    objFilter: searchData.getQuery(),
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Rows, RecordsetCount } = res as any
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

getTableData()

function toEdit(row: any) {
  editRef.value.open({
    data: row,
    type: ModelType.edit,
  })
}

function toCreate() {
  editRef.value.open({
    type: ModelType.add,
  })
}
async function submitEdit(formData: AccountForm, doLoading: doLoading) {
  try {
    doLoading(true)
    const isCreate = !formData.AccountObjID
    isCreate
      ? await userApi.AddAccount({
        accountInfo: formData,
      })
      : await userApi.UpdateAccount({
        accountInfo: formData,
      })
    getTableData()
    editRef.value.close()
    ElMessage.success({
      message: isCreate ? '新增成功' : '编辑成功',
      type: 'success',
    })
  }
  catch (e) {
    doLoading(false)
  }
}

async function toDel(row: AccountForm) {
  await ElMessageBox.confirm(`确定删除账户 ${row.Name} 吗？`, '提示', {
    type: 'warning',
  })
  await userApi.DeleteAccount({ accountObjID: row.AccountObjID })
  ElMessage.success({
    message: '删除成功',
    type: 'success',
  })
  getTableData()
}

const ownerOrgs = useOwnerOrgs()
const envOrgs = useEnvOrgs()
const AffiliatedOptions = computed(() => {
  switch (AffiliatedObjType.value) {
    case AccountType.OwnerOrg:
      return ownerOrgs.value
    case AccountType.EnvOrg:
      return envOrgs.value
    default:
      return []
  }
})

const showAffiliated = computed(() => {
  return AffiliatedObjType.value !== AccountType.Enterpris
})

const AffiliatedLabel = computed(() => {
  switch (AffiliatedObjType.value) {
    case AccountType.OwnerOrg:
      return '运维公司'
    case AccountType.EnvOrg:
      return '管理机构'
    default:
      return ''
  }
})
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol v-if="showAffiliated" :span="6">
              <ElFormItem :label="AffiliatedLabel">
                <el-tree-select
                  v-model="searchData['DIM.Authorizations.Filters.AffiliatedObjIDFilter']"
                  value-key="Code"
                  :data="AffiliatedOptions"

                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable check-strictly
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="账号">
                <ElInput v-model="searchData['DIM.Authorizations.Filters.CodeFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="姓名">
                <ElInput v-model="searchData['DIM.Authorizations.Filters.NameFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="联系电话">
                <ElInput v-model="searchData['DIM.Authorizations.Filters.ContactTelFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="消息推送电话">
                <ElInput v-model="searchData['DIM.Authorizations.Filters.MsgTelFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="showAffiliated ? 12 : 18" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
              <ElButton v-if="showAffiliated" type="success" @click="toCreate">
                新增
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table
          auto-resize border
          height="100%"
          :data="tableData"
          :loading="loading"
          :row-config="{ isCurrent: true }"
        >
          <VxeColumn type="seq" title="序号" width="80" />
          <VxeColumn field="AccountCode" title="账号" min-width="140" show-overflow />
          <VxeColumn field="Name" title="姓名" min-width="200" />
          <VxeColumn field="AffiliatedObjName" title="隶属单位" min-width="220" />
          <VxeColumn field="Roles" title="角色" min-width="150">
            <template #default="{ row }">
              <el-tag v-for="(item, index) in Object.keys(row.Roles).map((key) => row.Roles[key])" :key="index" class="mb-[5px] mr-[10px]">
                {{ item }}
              </el-tag>
            </template>
          </VxeColumn>
          <VxeColumn field="StateDescription" title="账号状态" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.StateID === 1" type="success">
                正常
              </el-tag>
              <el-tag v-else type="danger">
                禁用
              </el-tag>
            </template>
          </VxeColumn>
          <VxeColumn field="ExpirTime" title="有效期" width="140">
            <template #default="{ row }">
              {{ row.ExpirTime || '无期限' }}
            </template>
          </VxeColumn>
          <VxeColumn field="ContactTel" title="联系电话" width="180" />
          <VxeColumn field="MsgTel" title="消息推送电话" width="180" />
          <VxeColumn field="WxOpenID" title="绑定微信号" width="140" />
          <VxeColumn field="LogonTime" title="最后登录时间" width="180" />
          <VxeColumn field="operate" title="操作" width="160" fixed="right">
            <template #default="{ row }">
              <ElButton type="success" link @click="toEdit(row)">
                编辑
              </ElButton>
              <ElButton type="danger" link @click="toDel(row)">
                删除
              </ElButton>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
    <Edit ref="editRef" :is-no-ent="showAffiliated" :affiliated-obj-type="AffiliatedObjType" @submit="submitEdit" />
  </div>
</template>
